import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_module/core/app_env.dart';

class ImagePlaceholder {
  static const String smallPlaceholder =
      'images/common/image_shortrectangle_placeholder.png';
  static const String largePlaceholder =
      'images/common/image_longrectangle_placeholder.png';
  static const String squarePlaceholder =
      'images/common/image_square_placeholder.png';
  static const String avatarPlaceholder =
      'images/common/avatar_placeholder_white.png';
  static const String avatarGrayPlaceholder =
      'images/common/avatar_placeholder_white.png';
}

class ImageResourceFullURL {
  static String fullUrl(String? resource) {
    final _resource = resource ?? '';
    if (_resource.isEmpty) {
      return '';
    }
    if (_resource.startsWith(RegExp(r'^https?://', caseSensitive: false))) {
      return _resource;
    } else {
      final path =
          Uri.encodeComponent(_resource.replaceAll(RegExp(r'^/+'), ''));
      final baseUrl = (AppEnv.app2Env?.imgBaseURL ?? AppEnv.imgBaseURL)
          .replaceAll(RegExp(r'/+$'), '');
      final url = '$baseUrl/$path';
      return Uri.decodeComponent(url);
    }
  }
}

class YFNetworkImageProvider extends CachedNetworkImageProvider {
  YFNetworkImageProvider(String? resource)
      : super(ImageResourceFullURL.fullUrl(resource));
}

class YFNetworkImage extends CachedNetworkImage {
  YFNetworkImage(
      {String? resource,
      String? placeholderName = ImagePlaceholder.smallPlaceholder,
      BoxFit placeholderFit = BoxFit.cover,
      BoxFit? fit})
      : super(
          imageUrl: ImageResourceFullURL.fullUrl(resource),
          placeholder: (context, url) =>
              _placeholderWidget(placeholderName, placeholderFit),
          errorWidget: (context, url, error) =>
              _placeholderWidget(placeholderName, placeholderFit),
          fit: fit,
        );

  static Widget _placeholderWidget(String? name, BoxFit fit) {
    final _name = name ?? '';
    if (_name.isEmpty) {
      return SizedBox.shrink();
    }
    return Image.asset(
      _name,
      fit: fit,
    );
  }
}
